package com.mstanford.movie.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mstanford.movie.dao.MovieDao;
import com.mstanford.movie.utils.DataUtil;

public class RegisterServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		String memberEmail = request.getParameter("memberEmail");
		String memberPwd = request.getParameter("memberPwd");
		String memberGender = request.getParameter("memberGender");
		String code = request.getParameter("code");
		
		HttpSession session = request.getSession();
		Object obj = session.getAttribute("captcha");
		
		Map<String, String> map = new HashMap<String, String>();
		map.put("memberEmail", memberEmail);
		map.put("memberPwd", memberPwd);
		map.put("memberGender", memberGender);
		
		MovieDao dao = new MovieDao();
		
		// 判断邮箱是否被注册
		dao.queryHasMember(map);
		String hasMember = map.get("hasMember");
		
		// 判断验证码
		if(!code.equals(obj)) {
			map.put("codeError", "true");
		}
		
		if(!"true".equals(hasMember) && code.equals(obj)) {
			dao.addMember(map);
			map.put("add", "true");
		}
		
		// 返回Json格式信息
		String json = DataUtil.mapToJson(map);

		response.setContentType("application/json; charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		out.print(json);
		out.flush();
		out.close();
	}
}